import json
from datetime import datetime, timedelta
from pathlib import Path

# 数据存储文件
DATA_FILE = "menstrual_data.json"

def load_data():
    """加载存储的数据"""
    try:
        with open(DATA_FILE, 'r') as f:
            return json.load(f)
    except (FileNotFoundError, json.JSONDecodeError):
        return {"records": [], "cycle_length": 28}

def save_data(data):
    """保存数据到文件"""
    with open(DATA_FILE, 'w') as f:
        json.dump(data, f, indent=2)

def get_next_period(last_start, cycle_length):
    """计算下次月经开始日期"""
    return (datetime.strptime(last_start, "%Y-%m-%d") 
            + timedelta(days=cycle_length)).strftime("%Y-%m-%d")

def get_health_tips(phase):
    """根据生理阶段返回健康建议"""
    tips = {
        "menstrual": [
            "🌺 注意腹部保暖，可以使用暖宝宝",
            "💧 保持充足水分摄入",
            "🍖 多吃富含铁质的食物（红肉、菠菜等）",
            "🚫 避免剧烈运动和重体力劳动"
        ],
        "premenstrual": [
            "🍵 减少咖啡因和盐分摄入",
            "💤 保证充足睡眠",
            "🧘 尝试瑜伽或冥想缓解压力",
            "🥛 增加钙质摄入"
        ],
        "ovulation": [
            "🥗 注意营养均衡",
            "🏊 适合适度运动",
            "🚰 每日饮水量保持1.5-2L",
            "🔆 注意个人卫生"
        ],
        "regular": [
            "🏃‍♀️ 保持规律运动",
            "🥦 均衡饮食补充维生素",
            "📅 记录身体变化观察规律",
            "😊 保持心情愉悦"
        ]
    }
    return tips.get(phase, tips["regular"])

def main():
    data = load_data()
    
    while True:
        print("\n===== 姨妈期健康助手 =====")
        print("1. 记录新周期")
        print("2. 查看预测和提醒")
        print("3. 查看健康建议")
        print("4. 退出")
        
        choice = input("请选择操作 (1-4): ")
        
        if choice == "1":
            last_start = input("输入上次月经开始日期 (YYYY-MM-DD): ")
            try:
                # 验证日期格式
                
                data["records"].append(last_start)
                data["cycle_length"] = int(input("输入平均周期天数 (默认28): ") or 28)
                save_data(data)
                print("✅ 记录已保存")
            except ValueError:
                print("⚠️ 日期格式错误，请使用YYYY-MM-DD格式")
        
        elif choice == "2":
            if not data["records"]:
                print("⚠️ 请先记录月经周期")
                continue
                
            last_start = data["records"][-1]
            next_date = get_next_period(last_start, data["cycle_length"])
            today = datetime.now().date()
            days_until = (datetime.strptime(next_date, "%Y-%m-%d").date() - today).days
            
            print(f"\n📅 预测下次开始日期: {next_date}")
            if days_until <= 3 and days_until >= 0:
                print(f"⏰ 提醒: 预计{['今天', '明天', '后天'][days_until]}开始，请做好准备！")
                print("📌 注意事项:")
                print(" • 准备卫生用品\n • 避免安排重要活动\n • 注意饮食调理")
        
        elif choice == "3":
            phase = "regular"
            if data["records"]:
                last_date = datetime.strptime(data["records"][-1], "%Y-%m-%d")
                cycle_day = (datetime.now() - last_date).days
                
                if 0 <= cycle_day <= 5:
                    phase = "menstrual"
                elif 14 <= cycle_day <= 16:
                    phase = "ovulation"
                elif cycle_day >= data["cycle_length"] - 7:
                    phase = "premenstrual"
                    
            print("\n💡 今日健康建议:")
            for tip in get_health_tips(phase):
                print(f"• {tip}")
        
        elif choice == "4":
            print("👋 退出程序，记得照顾好自己哦～")
            break
            
        else:
            print("⚠️ 请输入有效的选项")

if __name__ == "__main__":
    # 首次运行创建数据文件
    if not Path(DATA_FILE).exists():
        save_data({"records": [], "cycle_length": 28})
    main()


